package com.meeting.controller;

import com.meeting.vo.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/files")
@Tag(name = "文件上传接口")
public class FileController {

    @Value("${file.upload-path:/upload/images/}")
    private String uploadPath;
    
    @Value("${file.access-path:/images/}")
    private String accessPath;
    
    @PostMapping("/upload")
    @Operation(summary = "上传文件")
    public Result uploadFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return Result.error("请选择要上传的文件");
        }
        
        try {
            // 创建目录
            File dir = new File(System.getProperty("user.dir") + uploadPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            // 获取文件后缀
            String suffix = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            
            // 生成新文件名
            String newFilename = UUID.randomUUID().toString().replace("-", "") + suffix;
            
            // 保存文件
            File destFile = new File(dir.getAbsolutePath() + File.separator + newFilename);
            file.transferTo(destFile);
            
            // 返回访问路径
            String fileUrl = accessPath + newFilename;
            log.info("文件上传成功，访问路径：{}", fileUrl);
            
            return Result.success(fileUrl);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }
} 